package com.caiden_micheal.dynamic.workflow.utils;

import com.alibaba.fastjson2.JSON;
import com.caiden_micheal.base.domain.workflow.ProcessEdge;
import com.caiden_micheal.dynamic.record.domain.DProcessRecord;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Data
public class EdgeParsingTool {
    private static final Logger logger = LoggerFactory.getLogger(EdgeParsingTool.class);

    public static List<ProcessEdge> parseEdgeList(String edgeStr) {
        try {
            List<ProcessEdge> processEdges = JSON.parseArray(edgeStr, ProcessEdge.class);
            return processEdges;
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
    }

    public static List<ProcessEdge> findEdgesByTargetNodeId(String targetNodeId, List<ProcessEdge> edgeList) {
        List<ProcessEdge> processEdgeList = new ArrayList<>();
        for (ProcessEdge processEdge : edgeList) {
            if (Objects.equals(processEdge.getTargetNodeId(), targetNodeId)) {
                processEdgeList.add(processEdge);
            }
        }
        return processEdgeList;
    }

    public static List<ProcessEdge> findEdgesBySourceNodeId(String sourceNodeId, List<ProcessEdge> edgeList) {
        List<ProcessEdge> processEdgeList = new ArrayList<>();
        for (ProcessEdge processEdge : edgeList) {
            if (Objects.equals(processEdge.getSourceNodeId(), sourceNodeId)) {
                processEdgeList.add(processEdge);
            }
        }
        return processEdgeList;
    }

    public static void processEnterEdge(String targetNodeId, String status, List<ProcessEdge> edgeList, List<DProcessRecord> dProcessRecordList) {
        for (ProcessEdge processEdge : edgeList) {
            if (Objects.equals(processEdge.getTargetNodeId(), targetNodeId)) {
                for (DProcessRecord dProcessRecord : dProcessRecordList) {
                    if (Objects.equals(dProcessRecord.getNodeId(), processEdge.getSourceNodeId())) {
                        processEdge.getProperties().setStatus(status);
                        break;
                    }
                }
            }
        }
    }
}
